var jsonobj1=""
var  resultiowk={};
var newdata=""
//查询
seahsdfs();
function seahsdfs() {
    console.log(sessionStorage.getItem("oldsysntractid"))
    $.ajax({
        url:root.inter.findCategoryDiscountForPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        async:false,
        data: {
            pageNum:1,
            pageSize:20,
           /* getQueryString('id')*/
            /*sessionStorage.getItem("id")*/
            customerCode:sessionStorage.getItem("id"),
            belContractId:sessionStorage.getItem("oldsysntractid")
        },
        success: function (result) {
            detaiist(result);
            $('.M-box3').pagination({
                pageCount: result.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.inter.findCategoryDiscountForPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        async:false,
                        data: {
                            pageNum:api.getCurrent(),
                            pageSize:20,
                            customerCode:sessionStorage.getItem("id")

                        },
                        success: function (result) {
                            detaiist(result);
                            $("#spu_all").attr("checked", false);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function detaiist(data) {
    newdata=data
    dataSource.splice(0, dataSource.length);//清空数组

    $.each(data.data.result, function (i, field) {
        var rowData = new Array();
        rowData.push(field.categoryName);
        rowData.push(field.brand);
        rowData.push(field.spuCode);
        rowData.push(field.productName);
        rowData.push(field.skuCode);
        rowData.push(field.saleAttriValue);
        rowData.push(field.modifyPriceWay);
        rowData.push(field.categoryDiscount);
        rowData.push(field.contractCategoryDiscountId);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);

    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "order": [[ 1, "desc" ]],
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span><td><input class="spuId" type="checkbox" name="spuId" value = "' + row[8] + '">' + row[0] + '</td></span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '';
                        if (row[6] == 10 && row[4] == "") {
                            var val = '<span style="display: inline-block;width: 210px;"><td ><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10" >折扣率</option></select></td><td><input style="width: 50px;" type="text" value="'+(row[7]*100).toFixed(0)+'"><span style="display: inline-block;">%</span></td>&nbsp;<td><a onclick="Cloes(\''+row[6]+'\',\''+row[8]+'\',\''+row[4]+'\',this)">修改</a></td></span>';
                        }else if (row[6] == 10 && row[4] != "") {
                            var val = '<span style="display: inline-block;width: 210px;"><td ><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20" >金额上调</option><option value="30">金额下调</option></select></td><td><input style="width: 50px;" type="text" value="'+(row[7]*100).toFixed(0)+'"><span style="display: inline-block;">%</span></td>&nbsp;<td><a onclick="Cloes(\''+row[6]+'\',\''+row[8]+'\',\''+row[4]+'\',this)">修改</a></td></span>';
                        } else if (row[6] == 20) {
                            var val = '<span style="display: inline-block;width: 210px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20" selected>金额上调</option><option value="30">金额下调</option></select></td><td><input style="width: 50px;" type="text" value="'+row[7]+'"><span  style="display: none">%</span></td><td>&nbsp;<a onclick="Cloes(\''+row[6]+'\',\''+row[8]+'\',\''+row[4]+'\',this)">修改</a></td></span>';
                        } else if (row[6] == 30) {
                            var val = '<span style="display: inline-block;width: 210px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20">金额上调</option><option value="30" selected>金额下调</option></select></td><td><input style="width: 50px;" type="text" value="'+row[7]+'"><span  style="display: none">%</span></td><td>&nbsp;<a onclick="Cloes(\''+row[6]+'\',\''+row[8]+'\',\''+row[4]+'\',this)">修改</a></td></span>';
                        }
                        return val;
                    },
                    "targets": 6
                },

                {
                    "render": function (data, type, row) {
                        var val = '<span><a onclick="detaildelete(\''+row[8]+'\')">删除</a></span>';
                        return val;
                    },
                    "targets": 7
                }
            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function() {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });

            }
        });
    };
}
//设置金额上下调金额默认为0
function jine(el) {
    if(newdata.data.result.length>0){
        $.each(newdata.data.result,function(k,v){
            if($(el).parent().find('select').val()==20){
                $(el).parent().find('input').val(0)
                var spanEl = el.nextSibling.nextSibling;
                $(spanEl).css({
                    display: "none"
                });


            } else if($(el).parent().find('select').val()==30){
                $(el).parent().find('input').val(0)
                var spanElq = el.nextSibling.nextSibling;
                $(spanElq).css({
                    display: "none"
                });

            }else if($(el).parent().find('select').val()==10){
                $(el).parent().find('input').val(100)
                var spanEldf = el.nextSibling.nextSibling;
                $(spanEldf).css({
                    display: "inline-block"
                });


            }

        });
    }


}
//一级二级三级
function goodslistCategory(categoryLevel) {
    console.log($("#class1").val())
    var categoryName = $("#class1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#class1").val(),
    }
    var succCallBack = function(data, status, response) {
        console.log("一级")
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>"
                $("#classUl1").html(classStr);
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#class1").focus(function() {
    $("#classUl1").show();
    goodslistCategory(1);
});
$(document).bind("click", function(e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#classUl1").hide()
        $("#class2").val();

    }
});
var oneCategoryId = "";
var twoCategoryId = "";
var threeCategoryId = "";
var goodslist_cantegory_id; //定义分类搜索条件
// 2,3,4级的模糊查询
function getNext_input(level, category_id) {
    console.log(category_id)
    if(level == 2) {
        console.log(category_id+'一级')
        oneCategoryId = category_id;
    } else if(level == 3) {
        console.log(category_id+'二级')
        twoCategoryId = category_id;
    } else if(level == 4) {
        console.log(category_id+'三级')
        threeCategoryId = category_id;
    }
    if(level == 4) {
        goodslist_cantegory_id = category_id;
    }
    if(level < 4) {
        console.log(level)
        $("#class" + level + "")[0].oninput = function() {
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#class" + level + "").val()
            }
            var succCallBack = function(data, status, response) {
                console.log("二级")
                console.log(data)
                if(data.errorCode == 0) {
                    if(data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for(var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if(data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#class" + level + "").focus(function() {
            $("#classUl" + level + "").show();
        });
        $(document).bind("click", function(e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#classUl" + level + "").hide()
            }
        });
    }

}

function nextClass(category_id, level, category_name) {
    $("#class" + level + "").val(category_name);
    if(level == 1) {
        $("#class2").val("");
        $("#class3").val("");
    } else if(level == 2) {
        $("#class3").val("");
    }
    var user_data = {
        parentCateId: category_id,
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if(data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + nextLevel + "").show();
                $("#classUl" + level + "").hide()
            }
        }
    }
    getNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

/*品牌选择*/
function myfFunction(){
     brandName = "";
     brandId = "";
    $.ajax({
        url: root.goodsInter.goods_getListBrand,
        cache: false,  //禁用缓存
        type: "POST",
        data: {
            brandName: $("#username").val().trim()
        },
        success: function (data) {
            console.log(data)
            var jsonObj =data.ListBrand;
            if(jsonObj==""){
                $("#tudfan").html("<li>无数据</li> ");
            }else {
                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    jsonobj1=jsonObj[i].brandId
                    brandIds=jsonObj[i].brandId
                    optionstring += "<li onclick='addCodeFun("+ jsonObj[i].brandId+ ",\""+jsonObj[i].brandName+ "\")'>"+jsonObj[i].brandName+ "</li>";
                }
                $("#tudfan").html(optionstring);
            }
        }
    });
}
//运营经理获取光标
$("#username").focus(function () {
    $("#tudfan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tudfan").length == 0 && $(e.target).closest("#username").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tudfan").hide()
    }
})
var brandName = "";
var brandId = "";
function addCodeFun(id,brand_name) {
    $("#tudfan").hide();
    $("#username").val(brand_name)
    brandName = brand_name;
    brandId = id;
}
function brand_sure() {
    sessionStorage.setItem("brand_name",brandName);
    sessionStorage.setItem("brand_id",brandId);
    $("#selectInp").css({
        display:"none"
    });
    addBrandName();
}
//渲染品牌名称
function addBrandName() {
    if(sessionStorage.getItem("brand_name")){
        $("#brandName").html(sessionStorage.getItem("brand_name"));
        $("#brandId").html(sessionStorage.getItem("brand_id"));
    }
}
//渲染属性名称
function addAttrName() {
    console.log(sessionStorage.getItem("attrObjCanch")+"##########");
    if(sessionStorage.getItem("attrObjCanch")){
        var attrObjCanch = JSON.parse(sessionStorage.getItem("attrObjCanch"));
        for(var i=0;i<attrObjCanch.length;i++){
            var attrValStr="";
            var attrIdsStr="";
            if(attrObjCanch[i].value.length != 0){
                for(var j=0;j<attrObjCanch[i].value.length;j++){
                    attrValStr += attrObjCanch[i].value[j].attri_value+";";
                    attrIdsStr +=attrObjCanch[i].value[j].attri_value_id+";";
                }
            }
            $("#appendAttr").remove();
            $("#attrTable").append('<tr id = "appendAttr"><th class="col-6-1 text-c">'+attrObjCanch[i].attribute_name+'</th><td><span>'+attrValStr+'</span><a onclick="addAttr('+attrObjCanch[i].attribute_id+",'"+attrIdsStr+"'"+')">添加</a></td></tr>')
        }
    }
}
function stoprop() {
    /*批量上架全选框阻止冒泡*/
    var timer = setTimeout(function() {
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num, $("#productManage"));
        clearTimeout(timer);
    }, 200)

    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}
function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
    if(num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}

//添加
function detailadd() {
    /*if( $("#class3").parent().find('input').val()==""){
        $.Huimodalalert('请选择分类！',2000);
        return false
    }
    */
    if( $("#class1").parent().find('input').val()=="" || $("#class2").parent().find('input').val()=="" || $("#class3").parent().find('input').val()==""){
        $.Huimodalalert('请选择分类！',2000);
        return false
    }
   /* if($("#class1").val()=="" && $("#class2").val()=="" && $("#class3").val()==""){
        $.Huimodalalert('请选择分类！',2000);
        return false
    }*/
    var brandIds=""
    var brandIdname=""
    if($("#username").val()==""){
            brandIds=""
            brandIdname=""
    }else {
        if(brandId!=""||brandName!=""){
            brandIds=brandId/*jsonobj1*/
            brandIdname=brandName
        }else {
            $.Huimodalalert('品牌不存在！',2000);
            return false;
        }
    }


    var objArr = [];
    var objJson = {
        "oneCategoryId": oneCategoryId,
        "twoCategoryId": twoCategoryId,
        "threeCategoryId": threeCategoryId,
        "categoryName": $("#class3").val(),
        "brand": brandIdname/*$("#username").val().trim()*/,
         "brandId":brandIds,
        "modifyPriceWay": '10',
        "saleAttriValue": "",
        "categoryDiscount": '1',
        "flag": '10',
        "customerId":sessionStorage.getItem("customerId")/*sessionStorage.getItem("customerId")*/,
        "customerCode":sessionStorage.getItem("id")/*sessionStorage.getItem("id")*/,
        "belContractId": sessionStorage.getItem("oldsysntractid")/*sessionStorage.getItem("contractID")*/,
        "createName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name/*JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name*/,
        "productCode":"",
        "spuCode": "",
        "productName": "",
        "skuCode": ""
        /*"createDate": "",
        "updateDate": ""*/

    };
    objArr.push(objJson);
    console.log(objArr);

    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url:root.inter.saveCategoryDiscount,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify(objArr),
        success: function (data) {
            if (data.errorCode==1){
                $.Huimodalalert(data.msg,2000);
            }
            seahsdfs();
           /* location.replace(location.href)*/
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
var customer_type = sessionStorage.getItem("customer_type");
var customertype=""
//修改
function Cloes(modifyPriceWay,id,skucode,el) {
    if (customer_type=="商店"){
        customertype=10
    }else {
        customertype=20
    }
    $.ajax({
        url:root.inter.updateBatchCategoryDiscount,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        async:false,
        data: {
            modifyPriceWay:$(el).parent().find('select').val(),
            categoryDiscount:$(el).parent().find('input').val(),
            contractCategoryDiscountId :id,
            skuCode:skucode,
            customerType:customertype

        },
        success: function (data) {
            seahsdfs();
            if(data.errorCode==0){
                $.Huimodalalert('修改成功！',2000);
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
//单个删除
function detaildelete(id) {
    console.log(id);
    var objArr = [];
    if (id.indexOf(",") != -1) {
        var split = id.split(",");
        for (var i = 0; i < split.length; i++) {
            objArr.push(Number(split[i]));
        }
    } else {
        objArr.push(id);
    }
    console.log(JSON.stringify(objArr))
    $.ajax({
        url:root.inter.delBatchCategoryDiscountByList,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify(objArr),
        success: function (data) {
            seahsdfs();
            $.Huimodalalert('删除成功！',2000);
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
//批量删除
function deleteyy() {
var spuIdArr=document.getElementsByName('spuId');
var str=""
for(var i=0; i < spuIdArr.length;i++){
    if(spuIdArr[i].checked==true){
       str+= spuIdArr[i].value+','
    }
    }
    str = str.substring(0, str.length - 1);
    detaildelete(str)

}
//查询结果页
function queryresults() {
    console.log($("#class1").val())
    var oneCategoryIds=""
    if($("#class1").val()==""){
        oneCategoryIds=""
    }else {
        oneCategoryIds=oneCategoryId
    }
    var twoCategoryIds=""
    if($("#class2").val()==""){
        twoCategoryIds=""
    }else {
        twoCategoryIds=twoCategoryId
    }
    var threeCategoryIds=""
    if($("#class3").val()==""){
        threeCategoryIds=""
    }else {
        threeCategoryIds=threeCategoryId
    }
    $.ajax({
        url:root.inter.findContractCategoryDiscountByCondition,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":20,
            "oneCategoryId":oneCategoryIds,
            "twoCategoryId":twoCategoryIds,
            "threeCategoryId":threeCategoryIds,
            "brand":$("#username").val().trim(),
            "spuCode":$("#spuCode").val().trim(),
            "productName":$("#spuName").val().trim(),
            "skuCode":$("#skuCode").val().trim(),
            "helpCode":$("#helpCode").val().trim(),//助记码
            "productCode":$("#Code").val().trim(),
            "customerCode":sessionStorage.getItem("id"),
            "belContractId":sessionStorage.getItem("oldsysntractid")
        }),
        success: function (result) {
            detaiist(result);
            $('.M-box3').pagination({
                pageCount: result.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.inter.findContractCategoryDiscountByCondition,
                        contentType: "application/json;charset=UTF-8",
                        ccache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":20,
                            "oneCategoryId":oneCategoryId,
                            "twoCategoryId":twoCategoryId,
                            "threeCategoryId":threeCategoryId,
                            "brand":$("#username").val().trim(),
                            "spuCode":$("#spuCode").val().trim(),
                            "productName":$("#spuName").val().trim(),
                            "skuCode":$("#skuCode").val().trim(),
                            "helpCode":$("#helpCode").val().trim(),//助记码
                            "productCode":$("#Code").val().trim(),
                        }),
                        success: function (result) {
                            detaiist(result);
                            $("#spu_all").attr("checked", false);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//搜索
function ditailquery(title,url) {
    if($("#spuCode").val().trim()!=""||$("#skuCode").val().trim()!=""||$("#Code").val().trim()!=""||$("#helpCode").val().trim()!=""||$("#spuName").val().trim()!=""||$("#skuName").val().trim()!=""){
        sessionStorage.setItem("threeCategoryId",threeCategoryId);
        sessionStorage.setItem("brandid",jsonobj1);
        sessionStorage.setItem("spuCode",$("#spuCode").val().trim());
        sessionStorage.setItem("skuCode",$("#skuCode").val().trim());
        sessionStorage.setItem("Code",$("#Code").val().trim());
        sessionStorage.setItem("helpCode",$("#helpCode").val().trim());
        sessionStorage.setItem("spuName",$("#spuName").val().trim());
        sessionStorage.setItem("skuName",$("#skuName").val().trim());

        var index = layer.open({
            type: 2,
            title: title,
            content: url
        });
        layer.full(index);
    }else {
        $.Huimodalalert('请填写详细信息！',2000);
    }



}
